import time
import uuid
from mylogger import logger
import sys
sys.path.append('../proto')
import llm_pb2
import llm_pb2_grpc
from http import HTTPStatus
import dashscope
import json
import requests

# time_load_start = time.time()
# logger.debug(f"加载模型用时:{time.time() - time_load_start}秒")


def get_qwen_answer(question):
    # # 老黄的
    # dashscope.api_key = 'sk-89d6e14895a04586a415655922225438'
    # 公司的
    dashscope.api_key = 'sk-bc5c3350c80f4a83b9d341fcbba00029'

    messages = [{'role': 'user', 'content': question}]

    response = dashscope.Generation.call(
        model='qwen-turbo',
        max_tokens=500,
        messages=messages,
        result_format='message',  # set the result to be "message" format.
    )
    if response.status_code == HTTPStatus.OK:
        print(response)
        try:
            return response.output.choices[0].message.content
        except:
            return ""
    else:
        print('http return not ok, Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))
        return ""


def get_wenxin_answer(question):
    # # 老黄的
    # api_key = "LUclgdmFQimRltYihKBUMchG"
    # secret_key = "vTycGsXKGNuP3CoxB70o3NywcKPQ6qFy"

    # 公司的
    api_key = "7punrigvE4vtOIkmuEpsOXoZ"
    secret_key = "cZM6rpfODrc4dX1kQO6x7CFKmrZOzcpu"

    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}"
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    if response.status_code != HTTPStatus.OK:
        logger.debug("获取token，http状态码不对"+str(response.status_code))
        return ""

    str_token = response.json().get("access_token")
    url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token={str_token}"  # 3.5 turbo

    messages = [{'role': 'user', 'content': question}]
    payload = {
        "max_tokens": 500,
        "messages": messages
    }
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
    if response.status_code != HTTPStatus.OK:
        logger.debug("百度文心一言大模型请求，返回的http状态码不对，"+str(response.status_code))
        return ""
    print(response.json())
    str_answer = response.json().get("result")
    str_answer = str_answer.replace("\r", "")
    str_answer = str_answer.replace("\n", "")
    logger.debug("答案是:"+str_answer)
    # str_answer = "西红柿炒鸡蛋的步骤如下：1. 准备好食材：鸡蛋、西红柿、菜籽油、葱花、蒜瓣、食盐和白糖。2. 将鸡蛋打散，加入适量食盐，搅拌均匀。3. 将西红柿洗净，切成块状。4. 锅中倒入适量菜籽油，待油热后，倒入鸡蛋液，翻炒至凝固，捞出备用。5. 锅中留少许底油，加入葱花和蒜瓣煸炒出香味。6. 加入西红柿块，翻炒至变软出汁。7. 加入适量白糖，继续翻炒均匀。8. 将之前炒好的鸡蛋块倒入锅中，翻炒均匀，使鸡蛋块都裹上西红柿的汤汁。9. 加入少许食盐，翻炒均匀即可。10. 最后，盛入盘中，撒上葱花点缀即可享用。完成以上步骤后，一道美味的西红柿炒鸡蛋就完成了。"
    return str_answer


class LlmHandler(llm_pb2_grpc.LLMChatApiServicer):
    def Ping(self, request, context):
        logger.debug(f"ping request")
        return llm_pb2.PingResponse(msg="pong")

    def GetLlmAnswer(self, request, context):
        if request.question == "":
            return llm_pb2.LlmResponse(answer="")
        logger.debug(f"问题是"+request.question)
        logger.debug(f"llm_type是" + request.llm_type)
        time_task_start = time.time()
        if request.llm_type == "qwen-turbo":
            str_answer = get_qwen_answer(request.question)
            print("str_answer:" + str_answer)
            logger.debug(f"GetLlmAnswer 千问turbo, 问题：{request.question}，用时:{time.time() - time_task_start}秒")
            return llm_pb2.LlmResponse(answer=str_answer)

        if request.llm_type == "wenxin-turbo":
            str_answer = get_wenxin_answer(request.question)
            print("str_answer:"+str_answer)
            logger.debug(f"GetLlmAnswer 文心一言turbo, 问题：{request.question}，用时:{time.time() - time_task_start}秒")
            return llm_pb2.LlmResponse(answer=str_answer)

        logger.debug(f"未匹配到" + request.llm_type)
        str_answer = get_qwen_answer(request.question)
        logger.debug(f"GetLlmAnswer 千问turbo, 问题：{request.question}，用时:{time.time() - time_task_start}秒")
        return llm_pb2.LlmResponse(answer=str_answer)




